<?php
/*
 * 降价模块, 复制自guide
 * @package    auto
 * @author     LSM
 * @copyright  Copyright (c) 2013 ixdcw team
 * @version    $Id: 3b23541af6c66fdb1ab308951dee8760c7843c11 $
 */
defined('IN_IXDCW') or exit('Access Denied');
/**
 * 降价模块
 */
class PriceModule extends BasicModule {

	/** @var 模块id */
	private $_moduleid;

	/** @var 条目ID */
	private $_itemid;

	/** @var string 表格 */
	private $_table;

	/** @var string 表格数据 */
	private $_tableData;

	/** @var 是否内容分表 */
	private $_split;

	/** @var array 可用字段 */
	private $_fields;


	/**
	 * constructor
	 * @param $moduleid
	 */
	function __construct($moduleid) {
		parent::__construct();
		global $table, $table_data, $MOD;
		$this->_moduleid  = $moduleid;
		$this->_table     = $table;
		$this->_tableData = $table_data;
		$this->_split     = $MOD['split'];
		$this->_fields    = array('cartypeid','itemid','catid','arbid','arcid','amid','areaid','level','title','introduce','keyword', 'hits', 'username','groupid', 'company', 'truename', 'telephone', 'price', 'favorableprice', 'mobile', 'address',  'starttime', 'endtime', 'editor', 'edittime', 'addtime', 'status', 'ip', 'linkurl','note');
	}

	public function setItemid($itemid) {
		$this->_itemid = $itemid;
	}

	public function getItemid() {
		return $this->_itemid;
	}

	public function getFields() {
		return $this->_fields;
	}

	/**
	 * 是否通过插入检测
	 * @param $post
	 * @return bool
	 */
	function pass($post) {
		if (!is_array($post)) return false;
		if(empty($post['arbid'][0])) return $this->err(lang('message->pass_arbid'));
		if(empty($post['arcid'][0])) return $this->err(lang('message->pass_arcid'));
		if(!$post['areaid']) return $this->err(lang('message->pass_quote_areaid'));
		if (strlen($post['title']) < 3) return $this->err(lang('message->pass_title'));
		if (isset($post['islink'])) {
			if (!$post['linkurl']) return $this->err(lang('message->pass_linkurl'));
		} else {
			if (!$post['content']) return $this->err(lang('message->pass_content'));
		}
        /**
         *验证各种必要信息不能为空。以及逻辑。
         */
        //电话号码是否是数字。
        if(!eregi("^[0-9]+$",$post['telephone'])){
            return $this->err(lang('message->pass_telshuzi'));
        }
        //验证优惠价小于现价
        if($post['price']<$post['favorableprice']){
            return $this->err(lang('message->pass_favorableprice'));
        }
        //开始时间，结束时间。。
        if($post['endtime']<$post['starttime']){
            return $this->err(lang('message->pass_tiemover'));
        }
//        //价格是否是数字。
//        if((!eregi("^[0-9]+$",$post['price']))&&(!eregi("^[0-9]+$",$post['favorableprice']))){
//            return $this->err(lang('message->pass_pirce_num'));
//        }
		return true;
	}

	/**
	 * 设置符合内容的值
	 * @param $post
	 * @return array|mixed
	 */
	function set($post) {
		global $MOD, $DT_TIME, $DT_IP, $_username, $_userid;
		$thumbSeName      = $this->_moduleid . '_thumb';
		$post['islink']   = isset($post['islink']) ? 1 : 0;
		$post['addtime']  = (isset($post['addtime']) && $post['addtime']) ? strtotime($post['addtime']) : $DT_TIME;
        //降价开始时间，结束时间的时间戳。
        $post['starttime']  = (isset($post['starttime']) && $post['starttime']) ? strtotime($post['starttime']) : $DT_TIME;
        $post['endtime']  = (isset($post['endtime']) && $post['endtime']) ? strtotime($post['endtime']) : $DT_TIME;

		$post['edittime'] = $DT_TIME;
		$post['title']    = trim($post['title']);
		$post['content']  = stripslashes($post['content']);
		if ($post['content'] && isset($post['clear_link']) && $post['clear_link']) {
			$post['content'] = Post::clearLink($post['content']);
		}
		if ($post['content'] && isset($post['save_remotepic']) && $post['save_remotepic']) {
			$post['content'] = Post::saveRemote($post['content']);
		}
		if ($post['content'] && $post['thumb_no'] && !$post['thumb']) {
			$post['thumb'] = Post::saveThumb($post['content'], $post['thumb_no'], $MOD['thumb_width'], $MOD['thumb_height']);
		}
		if (strpos($post['content'], 'pagebreak') !== false) {
			$post['content'] = str_replace(array('[pagebreak]</p>', '<p>[pagebreak]', '[pagebreak]</div>', '<div>[pagebreak]'), array('</p>[pagebreak]', '[pagebreak]<p>', '</div>[pagebreak]', '[pagebreak]<div>'), $post['content']);
		}
		if ($post['content'] && !$post['introduce'] && $post['introduce_length']) {
			$post['introduce'] = addslashes(Post::intro($post['content'], $post['introduce_length']));
		}

		if ($post['arbid'][0]){
			foreach($post['arbid'] as $v){if(!preg_match("/^\d*$/",$v)){$post['arbid']='';}}
			sort($post['arbid']);
			$post['arbid'] = implode(',',$post['arbid']);
			$sql = 'select distinct(acid) from xd_auto_model where arbid in ('.$post['arbid'].')';
			$acid = $this->_db->getAll($sql);
			$level = PCache::read('autoCategory-level.php');
			foreach($acid as $v){
				if($v['acid'] != 0){
					$post['acid'][] = $v['acid'];
					$post['acid'][] = $level[$v['acid']]['parentid'];
				}
			}
			$post['acid'] = array_flip(array_flip($post['acid']));
			sort($post['acid']);
			$post['acid'] = implode(',',$post['acid']);
		} else {
			$post['arbid'] = '';
			$post['arcid'] = '';
			$post['amid'] = '';
		}
		if ($post['arcid'] && $post['arbid']) {
			foreach ($post['arcid'] as $v) {
				if (!preg_match("/^\d*$/", $v)) {
					$post['arcid'] = '';
				}
			}
			sort($post['arcid']);
			$post['arcid'] = implode(',', $post['arcid']);
		} else {
			$post['arcid'] = '';
			$post['amid'] = '';
		}
		if ($post['arcid'] && $post['arbid'] && $post['amid']) {
			foreach ($post['amid'] as $v) {
				if (!preg_match("/^\d*$/", $v)) {
					$post['amid'] = '';
				}
			}
			sort($post['amid']);
			$post['amid'] = implode(',', $post['amid']);
		} else {
			$post['amid'] = '';
		}
		if ($this->_itemid) {
			// 处理新传入的img
			$r = $this->getOne();
			ThumbUpload::clearPicture($thumbSeName, $post['thumb'], $r['thumb'], $_userid);
			$post['editor'] = $_username;
			$new            = $post['content'];
			$old            = $r['content'];
			EditorUpload::clearDiff($new, $old, $_userid);
		} else {
			$post['ip'] = $DT_IP;
			ThumbUpload::clearPicture($thumbSeName, $post['thumb'], '', $_userid);
		}
		if (!defined('DT_ADMIN')) {
			$content = $post['content'];
			unset($post['content']);
			$post            = Str::htmlSpecialChars($post);
			$post['content'] = Str::safe($content);
		}
		$post['content'] = addslashes($post['content']);
		return $post;
	}

	/**
	 * 获取一条数据
	 * @return array|void
	 */
	function getOne() {
		$content_table = content_table($this->_moduleid, $this->_itemid, $this->_split, $this->_tableData);
		return $this->_db->getOne("SELECT * FROM {$this->_table} a,{$content_table} c WHERE a.itemid=c.itemid and a.itemid=$this->_itemid");
	}

	/**
	 * 获取列表
	 * @param string $condition 实际sql
	 * @param string $order 排序方式
	 * @param string $cache 缓存读取
	 * @return array
	 */
	function getList($condition = 'status=3', $order = 'addtime DESC', $cache = '',$_pagesizes) {
		global $MOD, $items;
		$num   = $this->_db->count($this->_table, $condition, $cache);
        //总条数
		$items = $num;
        $this->_pn->recordsPerPage($this->_pagesize);
		$this->_pn->records($num);
		$sql = "SELECT * FROM {$this->_table}";
		$sql .= $condition ? " WHERE {$condition}" : '';
		$sql .= $order ? " ORDER BY {$order}" : '';
        if($_pagesizes && $_pagesizes!=0){
            $this->_pagesize=$_pagesizes;
            $sql .= " LIMIT " . ($this->_pn->getPage() - 1) * $this->_pagesize . ',' . $this->_pagesize;
        }
		$lists  = $catids = $CATS = array();
		$result = $this->_db->query($sql, $cache);
		while ($r = $this->_db->fetchArray($result)) {
			$r['adddate']  = timetodate($r['addtime'], 5);
			$r['editdate'] = timetodate($r['edittime'], 5);
			$r['alt']      = $r['title'];
			$r['title']    = set_style($r['title'], $r['style']);
			if (!$r['islink'] && !strpos($r['linkurl'], '://')) $r['linkurl'] = $MOD['linkurl'] . $r['linkurl'];
			$catids[$r['catid']] = $r['catid'];
			$lists[]             = $r;
		}
        //查询车等级的信息。
//		if ($catids) {
//			$result = $this->_db->query("SELECT catid,catname,linkurl FROM {$this->_db->pre}category WHERE catid IN (" . implode(',', $catids) . ")");
//			while ($r = $this->_db->fetchArray($result)) {
//				$CATS[$r['catid']] = $r;
//			}
//			if ($CATS) {
//				foreach ($lists as $k => $v) {
//					$lists[$k]['catname'] = $v['catid'] ? $CATS[$v['catid']]['catname'] : '';
//					$lists[$k]['caturl'] = $v['catid'] ? $MOD['linkurl'].'?catid='.$v['catid'] : '';
//				}
//			}
//		}
//        return $sql;
		return $lists;
	}
    //得到SQL
    public function getSQLInfo($car_lev,$cityid,$order){
        $sql="select * from xd_price p,xd_auto_rank_car r";
        $sql.=" where status=3 and p.arcid = r.arid and r.level in ($car_lev)";
        if($cityid&&$cityid!=0){
            $sql.=" and areaid=".$cityid;
        }
        if($order){
            $sql.=$order;
        }
        return $sql;
    }
	/**
	 * 添加数据
	 * @param $post
	 */
	function add($post) {
		global $MOD;
		$post = $this->set($post);
		$this->_db->query(Sql::insert($this->_table, $post, $this->_fields));
		$this->_itemid = $this->_db->insertId();
		$content_table = content_table($this->_moduleid, $this->_itemid, $this->_split, $this->_tableData);
        //执行插入后，又对应的更新的表
		$this->_db->query("INSERT INTO {$content_table} (itemid,content) VALUES ('$this->_itemid', '$post[content]')");
		$this->update($this->_itemid, $post, $post['content']);
		if ($post['status'] == 3 && $post['username'] && $MOD['credit_add']) {
			credit_add($post['username'], $MOD['credit_add']);
			credit_record($post['username'], $MOD['credit_add'], 'system', lang('my->credit_record_add', array($MOD['name'])), 'ID:' . $this->_itemid);
		}
		clear_upload($post['content'] . $post['thumb'], $this->_itemid);
		return $this->_itemid;
	}

	/**
	 * 编辑
	 * @param $post
	 * @return bool
	 */
	function edit($post) {

		$this->delete($this->_itemid, false);
		$post = $this->set($post);

		$this->_db->query(Sql::update($this->_table, $post, "itemid={$this->_itemid}", '', $this->_fields));
		$content_table = content_table($this->_moduleid, $this->_itemid, $this->_split, $this->_tableData);
		$this->_db->query(Sql::update($content_table, "content='$post[content]'", "itemid=$this->_itemid"));
		$this->update($this->_itemid, $post, $post['content']);
		clear_upload($post['content'] . $post['thumb'], $this->_itemid);
		return true;
	}
	/**
	 * 更新
	 * @param        $itemid
	 * @param array  $item
	 */
	function update($itemid, $item = array()) {
		$item or $item = $this->_db->getOne("SELECT * FROM {$this->_table} WHERE itemid=$itemid");
		$upsql = self::updateQuote($item,$itemid);
		$keyword        = $item['title'] . ',' . str_replace(' ', ',', $item['tag']) . ',' . strip_tags(cat_pos($item['catid'], ','));
		$keyword        = str_replace("//", '', addslashes($keyword));
		$item['itemid'] = $itemid;
		$linkurl        = $item['islink'] ? $item['linkurl'] : url('price/show', 'itemid='.$itemid);
		$sql            = "keyword='$keyword',linkurl='$linkurl'".$upsql;
		$this->_db->query(Sql::update($this->_table, "$sql", "itemid=$itemid"));
	}

	/**
	 * 对导入数据进行处理
	 * @param        $itemid
	 * @param array  $item
	 */
	function updateQuote($item,$itemid) {
		if ($item['arbid']){
			if(is_array($item['arbid'])){
				$item['arbid'] = implode(',',$item['arbid']);
			}
			$sql = 'select distinct(acid) from xd_auto_model where arbid in ('.$item['arbid'].')';
			$acid = $this->_db->getAll($sql);
			$level = PCache::read('autoCategory-level.php');
//			foreach($acid as $v){
//				if($v['acid'] != 0){
//					$items['acid'][] = $v['acid'];
//					$items['acid'][] = $level[$v['acid']]['parentid'];
//				}
//			}
//			$items['acid'] = array_flip(array_flip($items['acid']));
//			sort($items['acid']);
//			if(is_array($items['acid'])){
//			   $acid = implode(',',$items['acid']);
//			}
//			if(!$acid || !$acid[0]){
//				$acid = '';
//			}else{
//				$upsql.= ",acid='$acid'";
//			}
		}
		$t = $this->_db->getOne("SELECT content FROM {$this->_tableData} WHERE itemid=$itemid");
		if(preg_match("/<strong>是否有现车：<.*strong>(.*)<br.*>[\w\W]*<strong>经销商售价：<.*strong>(.*) 万元<br.*>[\w\W]*<strong>经销商名称：<.*strong>(.*)<br.*>[\w\W]*<strong>经销商地址：<.*strong>(.*)<br.*>[\w\W]*<strong>经销商电话：<.*strong>(.*)[\w\W]*[<br.*>]?[\w\W]*<.*p>/i",$t['content'],$str)){
			$iscar   = strip_tags($str['1']);
			$price   = strip_tags($str['2']);
			//$company = strip_tags($str['3']);
			$address = strip_tags($str['4']);
			$tel     = strip_tags($str['5']);
		}
	     $content = Str::htmlSpecialChars(preg_replace("/<p><.*strong>更多详情请咨询经销商[\w\W]*/i",'',$t['content']));
		$this->_db->query("update {$this->_tableData} set content = '".$content."' where itemid=$itemid");
		if($iscar == '有现车'){$iscar = 0;}
		if($iscar == '少量现车'){$iscar = 1;}
		if($iscar == '现车充足'){$iscar = 2;}
		if($iscar == '无现车'){$iscar = 3;}
		if($iscar){$upsql.= ",iscar='$iscar'";}
		if($price){$upsql.= ",price='$price'";}
		//if($company){$upsql.= ",company='$company'";}
		if($address){$upsql.= ",address='$address'";}
		if($tel){$upsql.= ",tel='$tel'";}
		return $upsql;
	}
    //更改过期的降价信息状态
    public function ChangeStatus(){
        //原装SQL先查询出时间来。
        $price_list=self::getList('status=3','endtime','',0);
        //获取当前时间的时间戳。
        $nowtime=time();
        //循环对比。
        for($i=0;$i<count($price_list);$i++){
            if($nowtime>$price_list[$i]['endtime']){
                $update_sql="update xd_price set status=4 where itemid=".$price_list[$i]['itemid'];
                $this->_db->getAll($update_sql);
            }
        }
    }

	/**
	 * 回收站
	 * @param $itemid
	 * @return bool
	 */
	function recycle($itemid) {
		if (is_array($itemid)) {
			foreach ($itemid as $v) {
				$this->recycle($v);
			}
		} else {
			$this->_db->query(Sql::update($this->_table, "status=0", "itemid=$itemid"));
			$this->delete($itemid, false);
			return true;
		}
	}

	/**
	 * 还原
	 * @param $itemid
	 * @return bool
	 */
	function restore($itemid) {
		if (is_array($itemid)) {
			foreach ($itemid as $v) {
				$this->restore($v);
			}
		} else {
			$this->_db->query(Sql::update($this->_table, "status=3", "itemid=$itemid"));
			return true;
		}
	}

	/**
	 * 删除条目
	 * @param      $itemid
	 * @param bool $all
	 */
	function delete($itemid, $all = true) {
		if (is_array($itemid)) {
			foreach ($itemid as $v) {
				$this->delete($v, $all);
			}
		} else {
			$this->_itemid = $itemid;
			$r             = $this->getOne();
			if ($all) {
				$userid = get_user($r['username']);
				if ($r['thumb']) PictureUpload::deletePicture($r['thumb'], $userid);
				if ($r['content']) EditorUpload::clearDiff('', $r['content'], $userid);
				$this->_db->query(Sql::delete($this->_table, "itemid=$itemid"));
				$content_table = content_table($this->_moduleid, $this->_itemid, $this->_split, $this->_tableData);
				$this->_db->query(Sql::delete($content_table, "itemid=$itemid"));
			}
		}
	}

	/**
	 * 检测
	 * @param $itemid
	 * @return bool
	 */
	function check($itemid) {
		global $_username, $DT_TIME;
		if (is_array($itemid)) {
			foreach ($itemid as $v) {
				$this->check($v);
			}
		} else {
			$this->_itemid = $itemid;
			$this->_db->query(Sql::update($this->_table, "status=3,hits=hits+1,editor='$_username',edittime=$DT_TIME", "itemid=$itemid"));
			return true;
		}
	}

	/**
	 * 未通过审核
	 * @param $itemid
	 * @return bool
	 */
	function reject($itemid) {
		global $_username, $DT_TIME;
		if (is_array($itemid)) {
			foreach ($itemid as $v) {
				$this->reject($v);
			}
		} else {
			$this->_db->query(Sql::update($this->_table, "status=1,editor='$_username'", "itemid=$itemid"));
			return true;
		}
	}

	/**
	 * 清空
	 * @param string $condition
	 */
	function clear($condition = 'status=0') {
		$result = $this->_db->query("SELECT itemid FROM {$this->_table} WHERE $condition ");
		while ($r = $this->_db->fetchArray($result)) {
			$this->delete($r['itemid']);
		}
	}

	/**
	 * 级别设置
	 * @param $itemid
	 * @param $level
	 */
	function level($itemid, $level) {
		$itemids = is_array($itemid) ? implode(',', $itemid) : $itemid;
		$this->_db->query(Sql::update($this->_table, "level=$level", "itemid IN ($itemids)"));
	}

}